﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using MidiSheetMusic;

public class NoteSound : MonoBehaviour
{
    public MidiNote note;
    private bool isPlayed;
    private byte[] noteOn, noteOff;

    IEnumerator Start()
    {
        yield return new WaitUntil(delegate ()
        {
            return note != null;
        });

        noteOn = new byte[]
        {
            (byte)(0x90 | note.Channel),
            (byte)note.Number,
            (byte)note.Velocity
        };

        noteOff = new byte[]
        {
            (byte)(0x80 | note.Channel),
            (byte)note.Number,
            0x00
        };
    }

    void Update()
    {
        if (MidiDriver.sharedInstance == null)
            return;
        if (!isPlayed && GetComponent<RectTransform>().anchoredPosition.y <= 0)
        {
            isPlayed = true;
            MidiDriver.sharedInstance.Write(noteOn);
        }

        if (isPlayed && -GetComponent<RectTransform>().anchoredPosition.y >= note.Duration)
        {
            MidiDriver.sharedInstance.Write(noteOff);
            gameObject.SetActive(false);
        }
    }
}
